package com.zht.service.impl;

import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.zht.cache.RedisCache;
import com.zht.cache.RedisKeys;
import com.zht.config.CloopenConfig;
import com.zht.enmus.ErrorCode;
import com.zht.exception.ServerException;
import com.zht.service.SmsService;
import com.zht.utils.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements SmsService {

    // 依赖项合并自原先的 SmsService 和 SmsHelper
    private final RedisCache redisCache;
    private final CloopenConfig cloopenConfig;
    private final CCPRestSmsSDK sdk;

    @Autowired
    public SmsServiceImpl(RedisCache redisCache, CloopenConfig cloopenConfig) {
        this.redisCache = redisCache;
        this.cloopenConfig = cloopenConfig;
        this.sdk = new CCPRestSmsSDK();
        this.sdk.init(cloopenConfig.getRestURL(), "8883");
        this.sdk.setAccount(cloopenConfig.getAccountSID(), cloopenConfig.getAuthToken());
        this.sdk.setAppId(cloopenConfig.getAppID());
    }

    @Override
    public void sendVerificationCode(String phone) {
        // 1. 校验手机号格式
        if (!CommonUtils.checkPhone(phone)) {
            throw new ServerException(ErrorCode.SMS_INVALID_PHONE_NUMBER);
        }

        // 2. 生成4位验证码
        String code = String.valueOf(CommonUtils.generateCode());

        // 3. 将验证码存入 Redis，并设置 60 秒过期
        redisCache.set(RedisKeys.getSmsKey(phone), code, 60, TimeUnit.SECONDS);
        System.out.println("手机号 " + phone + " 的验证码 " + code + " 已存入 Redis，有效期60秒。");

        // 4. 调用私有方法发送短信
        String templateId = "1";
        String[] datas = {code, "1"};
        this.sendSmsViaCloopen(phone, templateId, datas);
    }

    @Override
    public void sendFakeCode(String phone) {
        // 1. 校验手机号格式
        if (!CommonUtils.checkPhone(phone)) {
            throw new ServerException(ErrorCode.SMS_INVALID_PHONE_NUMBER);
        }

        // 2. 生成4位验证码
        String code = String.valueOf(CommonUtils.generateCode());

        // 3. 将验证码存入 Redis，并设置 60 秒过期
        redisCache.set(RedisKeys.getSmsKey(phone), code, 60, TimeUnit.SECONDS);
        System.out.println("手机号 " + phone + " 的验证码 " + code + " 已存入 Redis，有效期60秒。");
    }

    /**
     * @param phone 手机号
     * @param templateId 模板ID
     * @param datas 模板参数
     */
    private void sendSmsViaCloopen(String phone, String templateId, String[] datas) {
        System.out.println("SmsServiceImpl: 准备发送短信 -> " + phone);
        HashMap<String, Object> result = sdk.sendTemplateSMS(phone, templateId, datas);

        if (!"000000".equals(result.get("statusCode"))) {
            // 发送失败，记录日志并抛出业务异常
            System.err.println("短信发送失败: " + result);
            throw new ServerException(ErrorCode.SMS_GATEWAY_SEND_FAILURE);
        }
        System.out.println("SmsServiceImpl: 短信发送成功");
    }
}